<template>
  <div v-loading="loading" :class="{'mobile-el-form':showMobilePage}" class="detail-order-info">
    <orderInfo :detail-data="detailData" />
    <GoodsInfo :data="detailData.goodsInfo || []"/>
    <LogisticsInfo :data="detailData.logisticsInfo" />
    <!-- 核销记录 -->
    <charge-off-record
      v-if="detailData && detailData.orderChannel"
      :records="detailData.financeRecord"
      :order-id="Number(orderId)"
      :client-name="detailData.clientName"
      :client-id="detailData.clientId"
      :is-not-add-account="hasRouteAuth('mengli:commerceOrder:addAccount') || isAdmin"
      :order-type="orderType"
      style="padding:0;"
      @getDetail="getData" />
    <div v-if="detailData && detailData.orderChannel" class="select-related-container" style="margin-top: 40px;">
      <InvoiceAndContract
        ref="ContractSelect"
        :show-empty="true"
        :is-edit="true"
        :title="'合同信息'"
        :sub-title="'关联合同'"
        :type="1"
        style="margin-top: 10px;"
        placeholder="请输入合同编号/合同名称"
        @changeSelect="changeSelect" />
    </div>
    <div v-if="detailData && detailData.orderChannel" class="select-related-container">
      <InvoiceAndContract
        ref="InvoiceSelect"
        :is-edit="true"
        :show-empty="true"
        :title="'发票信息'"
        :sub-title="'关联发票'"
        :is-disabled="false"
        :type="2"
        style="margin-top: 10px;"
        target-keyword="no"
        placeholder="请输入发票编号/发票号码"
        @changeSelect="changeSelect" />
    </div>
    <fixed-pagination>
      <div class="center">
        <el-button
          v-if="(hasRouteAuth('mengli:commerceOrder:edit') || isAdmin)"
          :disabled="beforeLastMonth(detailData.orderCreateTime)"
          type="primary"
          size="small"
          @click="toEdit">编辑订单</el-button>
        <el-button type="info" class="cancel-btn-style" size="small" @click="toBack"><span style="font-size:14px;">返回</span></el-button>
      </div>
    </fixed-pagination>
  </div>
</template>

<script>
// 组件
import Title from '@/components/Title';
import orderInfo from '@/components/Mengli/mengliOrder/commerceOrderInfo';
import GoodsInfo from './orderDetailModule/goodsInfo';
import LogisticsInfo from './orderDetailModule/logisticsInfo';
import InvoiceAndContract from '@/components/CreateOrder/InvoiceAndContract';
import ChargeOffRecord from '@/components/CreateOrder/orderDetail/chargeOffRecord';

// api
import { contractAndinvoiceInfo } from '@/api/mengliOrder';
import { getCommerceInfo } from '@/api/mengli';
import ElMessage from '@/utils/message';
import emptyImg from '@/assets/empty-data-icon.png';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';
export default {
  components: { Title, orderInfo, InvoiceAndContract, ChargeOffRecord, GoodsInfo, LogisticsInfo },
  data() {
    return {
      emptyImg,
      orderId: '',
      loading: false,
      detailData: {},
      operateLogs: [],
      orderType: null,
      clientWidth: ''
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    }
  },
  destroyed() {
    window.onresize = null;
  },
  created() {
    this.orderId = this.$route.params.id || '';
    this.orderType = Number(this.$route.query.type) || 0;
    this.getData();
  },
  methods: {
    hasRouteAuth,
    beforeLastMonth(date) {
      if (!date) return;
      const now = new Date();
      const year = now.getFullYear();
      const month = now.getMonth();
      // 截止操作日期至上个月
      const deadline = new Date(year, month - 1, 1, 0, 0, 0).getTime();
      return date * 1000 < deadline;
    },
    getData(muted = false) {
      this.loading = true;
      getCommerceInfo(this.orderId).then(res => {
        this.loading = false;
        if (res.data) {
          if (res.data.ipAry) {
            const ip = [];
            res.data.ipAry.forEach(i => {
              ip.push(`${i.ipFigure}/${i.ipSeries || '--'}`);
            });
            res.data.ipInfo = ip.join(',');
          }
          this.$nextTick(() => {
            if (this.$refs.ContractSelect) this.$refs.ContractSelect.setDefault(res.data.contract);
            if (this.$refs.InvoiceSelect) this.$refs.InvoiceSelect.setDefault(res.data.invoiceInfo);
          });
          this.detailData = res.data;
        }
        if (!res.data.isGoods && !muted) {
          this.$message.warning('库存里不存在该订单商品，无法关联成本及库存');
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    // 合同和发票修改
    changeSelect(selectData) {
      // this.toSubmit({ muted: true });
      const params = {
        id: this.orderId,
        orderType: this.orderType || 0
      };
      // 发票和合同
      const relatedIds = this.getRelatedIds();
      params.invoiceIds = relatedIds.invoiceIds;
      params.contractIds = relatedIds.contractIds;
      contractAndinvoiceInfo(params).then(res => {
        if (res.code === 200) {
          // ElMessage.success('关联成功');
          this.getData(true);
        } else {
          ElMessage.error(res.message);
        }
      });
    },
    // 获取合同和发票
    getRelatedIds() {
      const contractSelect = this.$refs.ContractSelect;
      const invoiceSelect = this.$refs.InvoiceSelect;
      let contractIds = [];
      let invoiceIds = [];
      if (contractSelect && contractSelect.selectData) {
        contractIds = contractSelect.selectData.map(i => i.id);
      }
      if (invoiceSelect && invoiceSelect.selectData) {
        invoiceIds = invoiceSelect.selectData.map(i => i.id);
      }
      return {
        contractIds: contractIds.join(','),
        invoiceIds: invoiceIds.join(',')
      };
    },
    toEdit() {
      this.$router.push({
        name: 'mengliOrderEdit',
        params: { id: this.orderId },
        query: { type: (this.detailData.orderChannel ? this.orderType : '21') || 0 }
      });
    },
    toBack() {
      const source = this.$route.query.source;
      const query = {};
      if (!source || source !== 'all') {
        query.type = 2;
      }
      this.$router.push({
        name: 'mengliOrder',
        query
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.detail-order-info {
  padding: 20px;
  background: #fff;
  padding-bottom: 55px;
  min-height: calc(100vh - 80px);
  &.mobile-el-form {
    padding-left: 12px;
    padding-right: 12px;
  }
  &::v-deep {
    .el-form-item .el-form-item__label {
      color: #999;
    }
    .el-form-item .el-form-item__content {
      color: #333;
    }
  }
}

.select-related-container {
  margin-top:30px;
  padding: 0;
  &::v-deep {
    .el-input__inner  {
      width: 240px;
      line-height: 16px;
    }
  }
}
.empty-container {
  text-align: center;
  position: relative;
  margin-top: 20px;
  img {
    width: 90px;
  }
  .empty-text {
    color: #999;
    max-width: 300px;
    font-size: 14px;
    margin: 0 auto;
  }
}
.fixed-foot {
  width: 100%;
  margin-bottom: 56px;
}
.tool-bar-container {
  position: fixed;
  bottom: 0px;
  right: 20px;
  height: 80px;
  width: 100%;
  z-index: 100;
  // background: linear-gradient(180deg, rgba(0,0,0,0), #fff,rgba(0,0,0,0));
  background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 56%, #FFFFFF 100%);
  border-radius: 0px 0px 8px 8px;
}
.container {
  // margin-bottom: 24px;
  // margin-top: 24px;
  width: 100%;
  border-radius: 0px 0px 8px 8px;
  display:flex;
  justify-content: center;
  bottom: 24px;
  position: absolute;
  &::v-deep {
    .el-button {
      margin-left: 16px;
    }
  }
}
</style>

